<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增入库结算单</div>
            <div v-else>
              <span
                class="text-sm mr-2"
                style="color: var(--el-text-color-regular)"
              >
                入库结算单编码:
              </span>
              <el-tag>{{ form.statementNo }}</el-tag>
            </div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" @click="submitForm">保 存</el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="100px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="结算单编码" prop="statementNo">
                    <el-input
                      v-model="form.statementNo"
                      placeholder="请输入结算单编码"
                      maxlength="18"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="承印单位" prop="printingUnit">
                    <!-- <el-input
                      v-model="form.printingUnit"
                      placeholder="请输入承印单位"
                      maxlength="18"
                    /> -->
                    <el-select
                      clearable
                      style="width: 100%"
                      v-model="form.printingUnit"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in production_printing_unit"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="入库日期" prop="statementTime">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.statementTime"
                      value-format="YYYY-MM-DD "
                      type="date"
                      placeholder="请选择日期"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="经办人" prop="operator">
                    <el-input
                      v-model="form.operator"
                      placeholder="请输入经办人"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="入库明细" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">入库明细</span>
          </template>
          <el-button
            v-if="!flag"
            style="margin-bottom: 10px"
            type="primary"
            size="small"
            @click="handleAddStorage"
          >
            新增
          </el-button>
          <el-table
            v-loading="loading"
            class="table-form"
            :data="statementDetails"
          >
            <el-table-column
              label="序号"
              width="60"
              type="index"
              align="center"
            ></el-table-column>
            <el-table-column
              label="生产单编码"
              align="center"
              width="150"
              prop="produceNo"
            ></el-table-column>
            <el-table-column
              label="出版编码"
              align="center"
              width="150"
              prop="pubNo"
            ></el-table-column>
            <el-table-column
              label="书刊编码"
              align="center"
              width="150"
              prop="bookCode"
            ></el-table-column>
            <el-table-column
              label="发货品种"
              min-width="300"
              align="center"
              prop="productName"
            ></el-table-column>
            <el-table-column
              label="订单数量"
              width="160"
              align="center"
              prop="orderCount"
            ></el-table-column>
            <el-table-column
              label="发货数量"
              width="160"
              align="center"
              prop="quantity"
            ></el-table-column>
            <el-table-column
              label="结算数量"
              align="center"
              width="110"
              prop="warehousingCount"
            >
              <template #default="scope">
                <el-input :disabled="flag" v-model="scope.row.warehousingCount">
                </el-input>
              </template>
            </el-table-column>
            >
            <el-table-column
              label="操作"
              v-if="!flag"
              align="center"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <!-- 领用库单明细 -->
    <orderList
      :visible="orderListOpen"
      @changeUpdate="changeOrderData"
      :orderSelectList="orderSelectList"
      @cancel="
        () => {
          orderListOpen = false;
        }
      "
    ></orderList>
  </div>
</template>

<script setup>
import {
  addSettlement,
  aditSettlement,
  getSettlementById,
} from "@/api/production/settlement.js";
import useUserStore from "@/store/modules/user";
import orderList from "./orderList.vue";
import useTagsViewStore from "@/store/modules/tagsView";
import { ElMessage } from "element-plus";
import { nextTick } from "vue";
const tagsViewStore = useTagsViewStore();
const userInfo = useUserStore();
const { proxy } = getCurrentInstance();
const { production_printing_unit } = proxy.useDict("production_printing_unit");
const route = useRoute();
const router = useRouter();
const orderSelectList = ref([]);
const orderListOpen = ref(false);
const activeNames = ["1", "2"];
const userRef = ref(null);
const flag = ref(false);
const searchType = ref("");
const loading = ref(false);
const data = reactive({
  form: {},
  statementDetails: [],
  rules: {
    printingUnit: [
      { required: true, message: "承印单位不能为空", trigger: "blur" },
    ],
    // statementNo: [
    //   { required: true, message: "结算单编码不能为空", trigger: "blur" },
    // ],
    operator: [{ required: true, message: "经办人不能为空", trigger: "blur" }],
    statementTime: [
      {
        required: true,
        message: "出库时间不能为空",
        trigger: ["blur", "change"],
      },
    ],
  },
});

const { form, rules, statementDetails } = toRefs(data);
nextTick(() => {});
if (route.query.id) {
  getSettlementById({ pid: route.query.id }).then((res) => {
    Object.assign(form.value, { ...res.data });
    statementDetails.value = res.data.statementDetails;
    if (route.query.info) {
      flag.value = true;
    }
  });
} else {
  flag.value = false;
  form.value = {};
  statementDetails.value = [];
}
nextTick(() => {
  form.value.operator = userInfo.name;
});

// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
};
// getCurrentDateTime();
form.value.printingUnit = "1";
// 新增入库明细
const handleAddStorage = () => {
  orderSelectList.value = statementDetails.value;
  orderListOpen.value = true;
};
// 选中的入库明细
const changeOrderData = (row) => {
  const codeSet = new Set(
    statementDetails.value.map((data) => data.deliveryDetailId)
  );
  row.forEach((item) => {
    if (!codeSet.has(item.deliveryDetailId)) {
      statementDetails.value.push({ ...item });
      codeSet.add(item.deliveryDetailId);
    }
  });
  orderListOpen.value = false;
};

// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    statementDetails.value = statementDetails.value.filter(
      (item) => item.deliveryDetailId != row.deliveryDetailId
    );
    proxy.$modal.msgSuccess("删除成功");
  });
};
// 确认
const submitForm = () => {
  userRef.value.validate((valid) => {
    if (valid) {
      if (route.query.id) {
        aditSettlement({
          ...form.value,
          statementDetails: statementDetails.value,
        }).then((res) => {
          ElMessage({
            message: "编辑成功",
            type: "success",
          });
          goBack();
        });
      } else {
        addSettlement({
          ...form.value,
          statementDetails: statementDetails.value,
        }).then((res) => {
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          goBack();
        });
      }
    }
  });
};
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
};
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}

:deep(.el-pagination) {
  position: unset;
}

.table-form :deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
